package com.song.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.song.view.dto.KeyModel;
import com.song.view.dto.Sm2Model;

import java.security.KeyPair;

public class Sm2Util {
    /**
     * 生成公钥、私钥
     * @param algorithm 算法
     * @return 密钥对
     */
    public static KeyModel genKey(String algorithm){
        KeyPair keyPair = SecureUtil.generateKeyPair(algorithm);
        String privateKey = Base64.encode(keyPair.getPrivate().getEncoded());
        String publicKey = Base64.encode(keyPair.getPublic().getEncoded());
        KeyModel keyModel = new KeyModel();
        keyModel.setPrivateKey(privateKey)
                .setPublicKey(publicKey);
        return keyModel;
    }

    /**
     * 生成SM2对象
     * @param privateKey 私钥
     * @param publicKey 公钥
     * @return
     */
    public static SM2 genSm2(String privateKey, String publicKey){
        return SmUtil.sm2(privateKey, publicKey);
    }

    /**
     * 签名
     * @param sm2
     * @param content 加密内容
     * @return
     */
    public static String sign(SM2 sm2, String content){
        return sm2.signHex(content);
    }

    /**
     * 验证签名
     * @param sm2
     * @param content 加密内容
     * @param sign 签名
     * @return
     */
    public static boolean verify(SM2 sm2, String content, String sign){
        return sm2.verifyHex(HexUtil.encodeHexStr(content), sign);
    }

    /**
     * 加密
     * @param sm2
     * @param content
     * @return
     */
    public static String encrypt(SM2 sm2, String content){
        return sm2.encryptBase64(content, KeyType.PublicKey);
    }

    /**
     * 解密
     * @param sm2
     * @param content
     * @return
     */
    public static String decrypt(SM2 sm2, String content){
        return sm2.decryptStr(content, KeyType.PrivateKey);
    }
}
